package com.example.onlineeducation.data.db.room

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase

/**
 * 1.必须是abstract且集成RoomDatabase
 * 2.使用@Databas注解
 */
@Database(entities = [SearchHistoryTable::class], version = 1, exportSchema = false)
abstract class RoomData : RoomDatabase() {

    abstract fun getSearchHistoryDao(): SearchHistoryDao
    companion object {
        //创建Book表，integer是正整型，real是浮点型，text是文本类型， blob是二进制类型。
        //primary key将id列为主键，autoincrement表示id列是自增长的。
        /*
        例子
        private const val createBooks = "create table tab_search_history(" +
                 "id integer primary key autoincrement," +
                 "author text," +
                 "prices real," +
                 "pages integer," +
                 "name text)"
        private const val addColumnBooks = "alter table Book add column category_id integer"
        */
//        private const val createSearchHistoryTable = "create table tab_search_history(" +
//                "search_history_id text primary key," +
//                "search_history_type text," +
//                "search_history_name text)"
//        private val MIGRATION_1_2 = object : Migration(1, 2) {
//            override fun migrate(database: SupportSQLiteDatabase) {
//                database.execSQL(createSearchHistoryTable)
//            }
//        }

        @Volatile
        private var INSTANCE: RoomData? = null
        fun getDataBase(context: Context): RoomData {
            return INSTANCE ?: synchronized(this) {
                val instance = Room.databaseBuilder(context.applicationContext, RoomData::class.java, "db_name")
                    .fallbackToDestructiveMigration()//未做迁移，则清空数据库
                    .allowMainThreadQueries()//允许主线程调用查询
                    .build()
                INSTANCE = instance
                instance
            }
        }
    }
}
